package main

import (
	"bufio"
	"fmt"
	"os"

	"imooc.com/ccmouse/gointro/pipeline"
)

func main() {
	pipeline.Init()
	fmt.Println(
		"Trying InMemSort and Merge nodes...")
	mergeDemo()

	pipeline.Init()
	fmt.Println("Generating random data...")
	writeData("small.in", 64)
	printFile("small.in")
}

func writeData(filename string, n int) {
	file, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	p := pipeline.RandomSource(n)

	writer := bufio.NewWriter(file)
	defer writer.Flush()

	pipeline.WriterSink(writer, p)
}

func printFile(filename string) {
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	p := pipeline.ReaderSource(file, -1)
	count := 0
	for v := range p {
		fmt.Println(v)
		count++
		if count >= 100 {
			break
		}
	}
}

func mergeDemo() {
	p := pipeline.Merge(
		pipeline.InMemSort(
			pipeline.ArraySource(
				3, 2, 6, 7, 4)),
		pipeline.InMemSort(
			pipeline.ArraySource(
				7, 4, 0, 3, 2, 13, 8)))
	for v := range p {
		fmt.Println(v)
	}
}
